<?php

namespace app\admin\app\controller;

use app\admin\app\model\Material;
use support\Db;
use support\Request;
use support\Response;
use app\admin\app\model\MaterialMerge;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 素材合并
 */
class MaterialMergeController extends Crud
{

    /**
     * @var MaterialMerge
     */
    protected $model = null;

    protected $dataLimit = 'personal';

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new MaterialMerge;
    }

    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('app/material-merge/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $rel = $this->validate($request);
            if ($rel !== true) {
                return $rel;
            }
            try {
                Db::transaction(function () use ($request) {
                    $data = $this->insertInput($request);
                    $number = $data['video_number'];
                    for ($i = 0; $i < $number; $i++) {
                        $data['video_number'] = 1;
                        $this->doInsert($data);
                    }
                });
            } catch (\Exception $e) {
                return $this->json(1, '报错失败' . $e->getMessage());
            }
            return $this->json(0, 'ok', []);
        }
        return view('app/material-merge/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $rel = $this->validate($request);
            if ($rel !== true) {
                return $rel;
            }
            return parent::update($request);
        }
        return view('app/material-merge/update');
    }

    protected function validate(Request $request)
    {
        if (!$request->post('is_random')) {
            $material_arr = explode(',', $request->post('material_ids'));
            $material = Material::whereIn('id', $material_arr)->where('group', 0)->first();
            if (empty($material)) {
                return $this->json(1, '必须选择主视频');
            }
        }
        return true;
    }

}
